package com.wswy.wzcx.ui.web;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.che.libcommon.ui.BaseFragment;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.R;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.utils.StatusBarCompat;
import com.wswy.wzcx.widget.JCInterface;

import com.tencent.smtt.sdk.*;

/**
 * Created by wangduheng26 on 2018/2/1.
 * wangduheng26@gmail.com
 */

public abstract class FragmentWebview extends BaseFragment {
    WebView mWebView;

    ProgressBar progressBar;
    boolean firstLoad = true;
    TextView tvTitle;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final Context context = container.getContext();
        LinearLayout root = new LinearLayout(context);
        root.setOrientation(LinearLayout.VERTICAL);
        FrameLayout frameLayout = new FrameLayout(context);
        mWebView = new WebView(context);
        mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        progressBar = new ProgressBar(context);
        frameLayout.addView(mWebView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        frameLayout.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

        View inflate = inflater.inflate(R.layout.layout_app_title, root, false);
        root.addView(inflate);
        inflate.findViewById(R.id.img_back).setVisibility(View.GONE);
        tvTitle = inflate.findViewById(R.id.tv_title);
        tvTitle.setText("交管12123常见问题");
        root.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        configWebView();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey("data")) {
            String url = arguments.getString("data");
            mWebView.loadUrl(url);
        }
    }

    @SuppressLint("JCInterface")
    private void configWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
        }

        WebSettings webSettings = mWebView.getSettings();
        //支持缩放，默认为true。
        webSettings.setSupportZoom(false);
        //调整图片至适合webview的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
        //设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);


        mWebView.setWebViewClient(getClient());
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvTitle.setText(title);
            }
        });
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.addJavascriptInterface(new JCInterface(getActivity()), "CcJsBridge");

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
                try {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    public WebViewClient getClient() {
        return new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!checkUrl(url)) {
                    firstLoad = false;
                    return super.shouldOverrideUrlLoading(view, url);
                }
                return true;
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showProgress(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissProgress();
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                dismissProgress();
            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                dismissProgress();
            }

        };


    }

    protected void showProgress(String url) {
        if (firstLoad) {
            firstLoad = false;
            progressBar.setVisibility(View.VISIBLE);
        } else {
            WebViewActivity.startWebview(getActivity(), url, true);
            firstLoad = true;
        }

    }

    private void dismissProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @TargetApi(Build.VERSION_CODES.N)
    public boolean checkUrl(WebResourceRequest request) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return checkUrl(request.getUrl().toString());
        }
        return false;
    }

    public boolean checkUrl(String url) {
        if (check(url)) {
            WebViewActivity.startWebview(getActivity(), url, true);
            return true;
        }
        return false;
    }


    private boolean check(String url) {
        String overrideUrl = getOverrideUrl();
        return TextUtils.isEmpty(overrideUrl) ||
                (!TextUtils.isEmpty(url) && url.contains(overrideUrl));
    }


    protected abstract String getOverrideUrl();
}
